package org.oschina.api.user.mail.queue;

import java.util.List;

import org.oschina.Constants;
import org.oschina.api.user.mail.model.UserMail;
import org.oschina.api.user.user.dao.UserDAO;
import org.oschina.helper.messagequeue.IMessageQueueHelper;
import org.oschina.queue.BaseQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 用户系统邮件推送队列
 */
@Component
public class UserSystemMailPushQueue extends BaseQueue {

	@Autowired
	private IMessageQueueHelper messageQueueHelper;
	@Autowired
	private UserDAO userDAO;
	
	private final static int BATCH_COUNT=10;
	
	@Scheduled(fixedDelay=1000)
	private synchronized void handle()
	{
		UserMail userMail=(UserMail)get(Constants.QUEUE_USER_SYSTEM_MAIL_PUSH, UserMail.class);
		if(userMail==null)
			return;
		
		int sum=0;
		if(userMail.getRole().equals(0))
			sum=userDAO.getCountByOnline();
		else
			sum=userDAO.getCountByOnlineAndRole(userMail.getRole());
		
		if(sum==0)
			return;
		
		int batch=sum/BATCH_COUNT;
		if(sum%BATCH_COUNT!=0)
			batch++;
		
		for(int i=0;i<batch;i++)
		{
			List<Integer> ids=null;
			if(userMail.getRole().equals(0))
				ids=userDAO.findIdByOnline(i*BATCH_COUNT, BATCH_COUNT);
			else
				ids=userDAO.findIdByOnlineAndRole(userMail.getRole(), i*BATCH_COUNT, BATCH_COUNT);
			
			for(Integer id:ids)
			{
				userMail.getTarget().setId(id);
				messageQueueHelper.send(Constants.QUEUE_USER_SIMPLE_MAIL_PUSH,userMail);
			}
		}
	}
}